// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------
import NodeCache from "node-cache"
import http from 'axios'

const Cache = new NodeCache();
class Tools {
    /**
     * 设置缓存，按需重载
     * @param string $cachename
     * @param mixed $value
     * @param int $expired
     * @return bool
     */
    static setCache($cachename, $value, $expired = 0) {
        return Cache.set($cachename, $value, $expired);
    }

    /**
     * 获取缓存，按需重载
     * @param string $cachename
     * @return mixed
     */
    static getCache($cachename) {
        return Cache.get($cachename);
    }

    /**
     * 清除缓存，按需重载
     * @param string $cachename
     * @return bool
     */
    static removeCache($cachename) {
        return Cache.del($cachename);
    }

    /**
     * SDK日志处理方法
     * @param string $msg 日志行内容
     * @param string $type 日志级别
     */
    static log($msg, $type = 'MSG') {
        Cache.put($type + ' - ' + $msg);
    }


    /**
     * 以get方式提交请求
     * @param $url
     * @return bool|mixed
     */
    static httpGet($url) {
        return new Promise((resolve, reject) => {
            http({
                url: $url,
                method: "GET",
            }).then(res => {
                if (res.status == 200) {
                    resolve(res.data);
                } else {
                    reject(res.statusText);
                }
            }).catch(err => {
                reject(err);
            });
        })
    }

    /**
     * 以post方式提交请求
     * @param string $url
     * @param array|string $data
     * @return bool|mixed
     */
    static httpPost($url, $data, $options = {}) {
        return new Promise((resolve, reject) => {
            http({
                url: $url,
                method: "POST",
                headers: {
                    "content-type": "application/json",
                },
                data: $data,
                ...$options
            }).then(res => {
                if (res.status == 200) {
                    resolve(res.data);
                } else {
                    reject(res.statusText);
                }
            }).catch(err => {
                reject(err);
            });
        })
    }
}

export default Tools;